package ch.subgate.spritestudio.tools;

import java.util.ArrayList;

import ch.subgate.spritestudio.R;
import ch.subgate.spritestudio.constants.Constants;
import ch.subgate.spritestudio.types.Sprite;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class SpritesAdapter extends BaseAdapter {
	private Context mContext;
	
	private ArrayList<Sprite> mSprites;
	
	public SpritesAdapter(Context context, ArrayList<Sprite> sprites) {
		mContext = context;
		mSprites = sprites;
	}

	@Override
	public int getCount() {
		return mSprites.size();
	}

	@Override
	public Object getItem(int position) {
		if (position > 0) {
			return mSprites.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view;
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
					Context.LAYOUT_INFLATER_SERVICE);
			view = inflater.inflate(R.layout.mainmenu_rowlayout, parent, false);
		}
		else {
			view = convertView;
		}
		
		Typeface face = Typeface.createFromAsset(
				mContext.getAssets(),
				"fonts/Roboto-Thin.ttf");
		
		ImageView imgview = (ImageView)view.findViewById(R.id.icon);
		TextView filename = (TextView)view.findViewById(R.id.filename);
		TextView filepath = (TextView)view.findViewById(R.id.filepath);
		filename.setTypeface(face);
		filepath.setTypeface(face);
		
		// If position is 0 return new picture button
		if (position == 0) {
			imgview.setBackgroundResource(R.drawable.newpicture);
			filename.setText("Create new picture");
			filepath.setText("");
		}
		else {
			Sprite sprite = mSprites.get(position);
			imgview.setImageBitmap(sprite.getBitmap());
			filename.setText(sprite.mFileName);
			filepath.setText(
					Environment.getExternalStorageDirectory().getPath()
					+ "/" + Constants.DEFAULT_MAIN_DIR
					+ "/" + sprite.mProjectName);
		}
		return view;
	}
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		mContext = null;
		mSprites = null;
	}

}
